package com.huika.dealontop.control.timelimit.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.google.gson.reflect.TypeToken;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.huika.dealontop.R;
import com.huika.dealontop.config.UrlConstants;
import com.huika.dealontop.control.base.BaseFra;
import com.huika.dealontop.control.homepage.Interface.StopRefreshInterface;
import com.huika.dealontop.control.homepage.activity.SearchActivity;
import com.huika.dealontop.control.shops.activity.ProductDetailsActivity1;
import com.huika.dealontop.control.timelimit.adapter.TimeGrouponAdapter;
import com.huika.dealontop.support.domain.TimeProductBean;
import com.huika.dealontop.support.http.FormResultRequest;
import com.huika.dealontop.support.http.JSONWrapAjaxParams;
import com.huika.dealontop.support.http.RequestResult;
import com.huika.dealontop.utils.GMapUtil;
import com.huika.dealontop.utils.UIUtils;
import com.huika.dealontop.views.TitleBarHelper;
import com.huika.huikalib.utils.NetUtil;
import com.huika.huikalib.utils.StringUtils;

import java.util.ArrayList;
import java.util.List;

public class TimeLimitFragment extends BaseFra implements BaseFra.OnInitShowListener, GMapUtil.MyLocationListener,
        StopRefreshInterface {
    private TimeGrouponAdapter nearbyGrouponAdapter;
    private List<TimeProductBean> NearbyGrouponList = new ArrayList<TimeProductBean>();
    private PullToRefreshListView mPullRefreshListView;
    private JSONWrapAjaxParams ajaxParams;
    private FormResultRequest<List<TimeProductBean>> request;
    private TextView homepage_tv_refresh_position;
    private ImageView homepage_iv_refresh;
    private boolean isForHomeDelivery;
    private boolean isForOrder;
    private boolean isForLimitRule;
    private boolean checknet;
    private int sortnum;
    private int areaId;
    private int categoryId;
    private int mCurrenSortIndex;
    private GMapUtil gMapUtil;

    @Override
    protected View inflaterView(LayoutInflater inflater, ViewGroup container, Bundle bundle) {
        View root = inflater.inflate(R.layout.frag_selection, container, false);
        return root;
    }

    @Override
    protected void initWidget(View parentView) {
        super.initWidget(parentView);
        TitleBarHelper titleBarHelper = new TitleBarHelper(getActivity(), R.string.common_empty, R.string
                .common_empty, R
                .string.selection_title);
        titleBarHelper.setRightImg(R.mipmap.search);
        titleBarHelper.setLeftGone();
        titleBarHelper.setOnRightImgClickListener(this);
        mPullRefreshListView = (PullToRefreshListView) parentView.findViewById(R.id.pull_refresh_lists);
        homepage_tv_refresh_position = (TextView) parentView.findViewById(R.id.homepage_tv_refresh_position);
        homepage_iv_refresh = (ImageView) parentView.findViewById(R.id.homepage_iv_refresh);
        homepage_iv_refresh.setOnClickListener(this);
        gMapUtil = new GMapUtil(getActivity(), this);
        gMapUtil.getLatestGeoAddress();
        gMapUtil.setStopRefreshAnim(this);
        SelectContentItemView();
    }

    @Override
    public void onResume() {
        super.onResume();
        startOverallLoading(mPullRefreshListView);
        executeGetNearbyGrouponPro();
    }

    /**
     * 点击列表条目的监听事件
     */
    private void SelectContentItemView() {
        mPullRefreshListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                checknet = false;
                CURRENT_PAGE = 1;
                executeGetNearbyGrouponPro();

            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                checknet = false;
                CURRENT_PAGE++;
                // 加载下一页
                ajaxParams.putCommonTypeParam("PageIndex", CURRENT_PAGE);
                executeRequest(request);
            }
        });
        mPullRefreshListView.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
        nearbyGrouponAdapter = new TimeGrouponAdapter(UIUtils.getContext());
        mPullRefreshListView.setAdapter(nearbyGrouponAdapter);

        mPullRefreshListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //点击商品
                String mProductID = nearbyGrouponAdapter.getItem(position - 1).getProductId() + "";
                Intent intent = new Intent(getActivity(), ProductDetailsActivity1.class);
                intent.putExtra(ProductDetailsActivity1.PRODUCT_ID, mProductID);
                intent.putExtra(ProductDetailsActivity1.PRODUCT_IMG, nearbyGrouponAdapter.getItem(position - 1).getProductPicUrl());
                showActivity(getActivity(), intent);
            }
        });
    }

    @Override
    protected void widgetClick(View v) {
        super.widgetClick(v);
        switch (v.getId()) {
            case R.id.left://返回

                break;
            case R.id.title_right_iv://跳入搜索页面
                Bundle bundle = new Bundle();
                bundle.putInt(SearchActivity.SEARCHCHOOSE_ID, 0);
                showActivity(getActivity(), SearchActivity.class, bundle);
                break;
            case R.id.homepage_iv_refresh:
                Animation animation = AnimationUtils.loadAnimation(getActivity(), R.anim.homepage_refresh_rotation);
                LinearInterpolator lir = new LinearInterpolator();
                animation.setInterpolator(lir);
                homepage_iv_refresh.startAnimation(animation);
                gMapUtil.getLatestGeoAddress();
                break;
        }
    }

    @Override
    protected void initData() {
        super.initData();
        CURRENT_PAGE = 1;
    }

    /**
     * 获取身边(附近)团购
     */
    private void executeGetNearbyGrouponPro() {
        double x = 0;
        double y = 0;
        if (mCurrenSortIndex > 0) {
            sortnum = mCurrenSortIndex + 1;
        } else {
            sortnum = 1;
        }
        if (areaId >= 0) {

        } else {
            areaId = 0;
        }
        if (categoryId >= 0) {

        } else {
            categoryId = 0;
        }
        if (new GMapUtil().getCurrentLat().equals("") || StringUtils.isEmpty(new GMapUtil().getCurrentLat()) || new
                GMapUtil().getCurrentLng().equals("") || StringUtils.isEmpty(new GMapUtil().getCurrentLng())) {
            x = 0.000000;
            y = 0.000000;
        } else {
            y = Double.valueOf(new GMapUtil().getCurrentLat());
            x = Double.valueOf(new GMapUtil().getCurrentLng());
        }
        // 刷新
        ajaxParams = new JSONWrapAjaxParams();
        ajaxParams.putCommonTypeParam("Latitude", x);//经度
        ajaxParams.putCommonTypeParam("Longitude", y);//维度
        ajaxParams.putCommonTypeParam("AreaId", areaId);//附近地区名称(默认值0，所有地区商品)
        ajaxParams.putCommonTypeParam("CategoryId", categoryId);//分类名称(默认值0，所有分类商品)
        ajaxParams.putCommonTypeParam("OrderBy", sortnum);//排序
        ajaxParams.putCommonTypeParam("PageSize", PAGE_SIZE);
        ajaxParams.putCommonTypeParam("PageIndex", CURRENT_PAGE);
        request = new FormResultRequest<List<TimeProductBean>>
                (UrlConstants
                        .BUYLIMITPRODUCTLIST, GetNearbyGrouponPro, this, new
                        TypeToken<RequestResult<List<TimeProductBean>>>() {
                        }.getType());
        request.setRequestParams(ajaxParams);
        executeRequest(request);
    }

    private Listener<RequestResult<List<TimeProductBean>>> GetNearbyGrouponPro = new
            Listener<RequestResult<List<TimeProductBean>>>() {
                @Override
                public void onResponse(RequestResult<List<TimeProductBean>> Result) {
                    dismissLoadingDialog();
                    stopOverallLoading();
                    hideEmptyLayView();
                    checknet = true;
                    if (checknet = true) {
                        mPullRefreshListView.onRefreshComplete();
                    }
                    int totalSize = Result.getTotalSize();
                    if (Result.flag == 1) {
                        if (Result != null && Result.getRs() != null) {
                            //无数据
                            if (CURRENT_PAGE == 1) {
                                NearbyGrouponList = Result.getRs();
                            } else {
                                NearbyGrouponList.addAll(Result.getRs());
                            }
                            nearbyGrouponAdapter.setGroup(NearbyGrouponList);
                            if (totalSize > 0) {// 无记录
                                hideEmptyLayView();
                                hideOverLay();
                            }
                        }
                    }
                    if (nearbyGrouponAdapter.getCount() <= 0 && totalSize <= 0) {
                        showEmptyLayView(mPullRefreshListView, R.string.Merchant_emptytuangou, R.mipmap
                                .emptyseach);
                    }
                    changeRefreshMode(totalSize);
                }
            };


    @Override
    public void onErrorResponse(VolleyError error) {
        super.onErrorResponse(error);
        checknet = true;
        dismissLoadingDialog();
        stopOverallLoading();
        if (CURRENT_PAGE == 1 && nearbyGrouponAdapter.getCount() <= 0 && NetUtil.hasAvailableNet(UIUtils.getContext()
        ) == false) {
            showNoNetView(mPullRefreshListView, reloaClickListener);
        } else if (CURRENT_PAGE == 1 && nearbyGrouponAdapter.getCount() <= 0 && NetUtil.hasAvailableNet(UIUtils
                .getContext()) ==
                true) {
            showEmptyLayView(mPullRefreshListView, R.string.Merchant_emptytuangou, R.mipmap
                    .emptyseach);
        }
        if (checknet = true) {
            mPullRefreshListView.onRefreshComplete();
        }
    }

    private View.OnClickListener reloaClickListener = new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // 第一页就加载失败了
            hideOverLay();
            startOverallLoading(mPullRefreshListView);
            executeGetNearbyGrouponPro();
        }
    };


    @Override
    public void onInitShow() {
//        hideOverLay();
//        startOverallLoading(mPullRefreshListView);
//        showLoadingDialog("");
//        executeGetNearbyGrouponPro();
    }

    private void changeRefreshMode(int totalSize) {
        if (totalSize == 0) {
            mPullRefreshListView.setMode(PullToRefreshBase.Mode.DISABLED);
        } else if (nearbyGrouponAdapter.getCount() >= totalSize) {
            mPullRefreshListView.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
        } else {
            mPullRefreshListView.setMode(PullToRefreshBase.Mode.BOTH);
        }
    }

    @Override
    public void getLatestAddress(String latestAddress) {
        homepage_tv_refresh_position.setText(latestAddress);
    }

    @Override
    public void stopRefresh() {
        if (homepage_iv_refresh == null || homepage_iv_refresh.getAnimation() == null) {
            return;
        }
        homepage_iv_refresh.clearAnimation();
    }
}
